package com.app.controller;


import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.app.mapper.*;
import com.app.model.*;
import com.app.service.IFwService;
import com.app.service.IUserFwJoinService;
import com.app.service.RedisService;
import com.app.util.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 小程序用户 与 房屋 绑定关联关系表 前端控制器
 * </p>
 *
 * @author yoominic
 * @since 2025-03-12
 */
@Api(tags = "小程序用户与房屋 绑定关联关系表")
@RestController
@RequestMapping("/userFwJoin")
public class UserFwJoinController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IUserFwJoinService userFwJoinService;

    @Autowired
    private IFwService fwService;

    @Autowired
    private RedisService redisService ;

    @Autowired
    private FwMapper fwMapper;


    @ApiOperation(value = "测试短信验证码接口", notes = "测试短信验证码接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "verificationCode", value = "验证码", required = true, dataType = "String")
    })
    @GetMapping("test/smsVerificationCodeTest")
    public Result smsVerificationCodeTest(HttpServletRequest request,String mobile,String verificationCode){
        //校验手机号和验证码
        if (mobile != null && verificationCode!=null){
            String key = "mobile_verification_code_" + mobile;
            String errKey = "mobile_verification_code_err_" + mobile;
            String verificationRedis = (String) redisService.get(key);
            if (verificationRedis != null) {
                String redisCode = (String) redisService.get(key);

                //验证码错误,记录到redis中，防止多次错误尝试
                if (!redisCode.equals(verificationCode)){
                    Integer errCount = (Integer) redisService.get(errKey);
                    if (errCount == null){
                        redisService.set(errKey, 1);
                        return Result.error("验证码错误！还剩"+(5-1)+"次机会！");
                    }
                    if (errCount<5){
                        redisService.set(errKey, errCount+1);
                        return Result.error("验证码错误！还剩"+(5-errCount)+"次机会！");
                    }else {
                        //锁定ip 一个小时
                        String ip = "send_sms_err_ip_"+request.getRemoteAddr();
                        redisService.set(ip, 1, 60*60);
                        //锁定手机号 一个小时
                        String username = "send_sms_err_phone_"+mobile;
                        redisService.set(username, 1, 60*60);
                        return Result.error("验证码错误次数过多，请稍后再试！");
                    }
                }
            }else {
                return Result.error("验证码已过期！");
            }
        }
        return Result.success("验证码正确！");
    }


    @Autowired
    private YonghuMapper yonghuMapper;

    @Autowired
    private TenantRelationshipMapper tenantRelationshipMapper;

    @ApiOperation(value = "小程序用户 与 房屋 绑定关联关系表 保存", notes = "小程序用户 与 房屋 绑定关联关系表 保存")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fwJoin", value = "房屋信息", required = true, dataType = "com.app.model.UserFwJoin")
    })
    @PostMapping("applet/saveUserFwJoin")
    public Result saveUserFwJoin(HttpServletRequest request, @RequestBody UserFwJoin fwJoin){
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error( "token不存在");
        }
        String userId =  StpUtil.getLoginIdByToken(token).toString();
//        String userId = "2";
        if (userId == null) {
            Result result = new Result(401, "登录失效");
            return result;
        }
        User user = userMapper.selectById(userId);
        if (user == null){
            return Result.error("用户不存在！");
        }
        //校验手机号和验证码
        if (fwJoin.getWechatBoundPhone() != null && fwJoin.getSmsVerificationCode()!=null){
            String key = "mobile_verification_code_" + fwJoin.getWechatBoundPhone();
            String errKey = "mobile_verification_code_err_" + fwJoin.getWechatBoundPhone();
            String verificationRedis = (String) redisService.get(key);
            if (verificationRedis != null) {
                String redisCode = (String) redisService.get(key);

                //验证码错误,记录到redis中，防止多次错误尝试
                if (!redisCode.equals(fwJoin.getSmsVerificationCode())){
                    Integer errCount = (Integer) redisService.get(errKey);
                    if (errCount == null){
                        redisService.set(errKey, 1);
                        return Result.error("验证码错误！还剩"+(5-1)+"次机会！");
                    }
                    if (errCount<5){
                        redisService.set(errKey, errCount+1);
                        return Result.error("验证码错误！还剩"+(5-errCount)+"次机会！");
                    }else {
                        //锁定ip 一个小时
                        String ip = "send_sms_err_ip_"+request.getRemoteAddr();
                        redisService.set(ip, 1, 60*60);
                        //锁定手机号 一个小时
                        String username = "send_sms_err_phone_"+fwJoin.getWechatBoundPhone();
                        redisService.set(username, 1, 60*60);
                        return Result.error("验证码错误次数过多，请稍后再试！");
                    }
                }
            }else {
                return Result.error("验证码已过期！");
            }
        }

        System.err.println("fwJoin:"+fwJoin.toString());
        System.err.println("fwId:"+fwJoin.getFwId());

        QueryWrapper<Fw> fwQueryWrapper = new QueryWrapper<>();
        fwQueryWrapper.eq("id", fwJoin.getFwId());
        Fw fw = fwService.getOne(fwQueryWrapper);
        if (fw == null){
            return Result.error("房屋不存在！");
        }


        if (fwJoin.getId() == null){

            QueryWrapper<Yonghu> yonghuQueryWrapper = new QueryWrapper<>();
            yonghuQueryWrapper.eq("unique_id", fw.getIdValue());
            List<Yonghu> yonghulist = yonghuMapper.selectList(yonghuQueryWrapper);
            for (Yonghu yonghu : yonghulist){
                yonghu.setWechatPhoneBindTime(LocalDateTime.now());
                yonghu.setWechatPhoneNumber(fwJoin.getWechatBoundPhone());
                yonghuMapper.updateById(yonghu);
            }

            QueryWrapper<TenantRelationship> tenantRelationshipQueryWrapper = new QueryWrapper<>();
            tenantRelationshipQueryWrapper.eq("unique_id", fw.getIdValue());
            tenantRelationshipQueryWrapper.orderByDesc("tenant_serial_number");
            tenantRelationshipQueryWrapper.last("limit 1");
            TenantRelationship tenantRelationship = tenantRelationshipMapper.selectOne(tenantRelationshipQueryWrapper);
            if (tenantRelationship != null) {
                tenantRelationship.setWechatBoundPhone(fwJoin.getWechatBoundPhone());
                tenantRelationship.setBoundTime(LocalDateTime.now());
                tenantRelationshipMapper.updateById(tenantRelationship);
            }

            fwJoin.setUserId(user.getId());
            fwJoin.setCreateTime(LocalDateTime.now());
            userFwJoinService.save(fwJoin);
        }else {
            userFwJoinService.updateById(fwJoin);
        }
        return Result.success("操作成功！");
    }


    @ApiOperation(value = "获取登录用户绑定的房屋信息", notes = "获取登录用户绑定的房屋信息")
    @GetMapping("applet/getLoginUserFwJoin")
    public Result getLoginUserFwJoin(HttpServletRequest request){

        String token = request.getHeader("token");
        if (token == null && StpUtil.getLoginIdByToken(token)==null) {
            return Result.error( "token不存在");
        }
        String userId =  StpUtil.getLoginIdByToken(token).toString();

        if (userId == null) {
            Result result = new Result(401, "登录失效");
            return result;
        }
//        String userId = "2";
        User user = userMapper.selectById(userId);
        if (user == null){
            return Result.error("用户不存在！");
        }
        List<Fw> list = fwMapper.getLoginUserJoinFws(user.getId());

        return Result.success(list);
    }


    @ApiOperation(value = "获取登录用户绑定的承租人信息", notes = "获取登录用户绑定的承租人信息")
    @GetMapping("applet/getLoginUserFwJoinYonghuInfo")
    public Result getLoginUserFwJoinYonghuInfo(HttpServletRequest request){

        String token = request.getHeader("token");
        if (token == null && StpUtil.getLoginIdByToken(token)==null) {
            return Result.error( "token不存在");
        }
        String userId =  StpUtil.getLoginIdByToken(token).toString();
        if (userId == null) {
            Result result = new Result(401, "登录失效");
            return result;
        }
//        String userId = "2";
        User user = userMapper.selectById(userId);
        if (user == null){
            return Result.error("用户不存在！");
        }
        List<Fw> list = fwMapper.getLoginUserFwJoinYonghuInfo(user.getId());
        for (Fw fw : list){
            String familyMembersJsonStr = fw.getFamilyMembersJsonStr();
            if (familyMembersJsonStr != null && !familyMembersJsonStr.equals("")){
                JSONArray array = JSONArray.parseArray(familyMembersJsonStr);
                for (int i = 0; i < array.size(); i++){
                    JSONObject obj = array.getJSONObject(i);
                    obj.put("id", i+1);
                }
                fw.setFamilyMembers(array);
                fw.setFamilyMembersCount(array.size());
            }
        }

        return Result.success(list);
    }


}

